import {
	// serializeParams
	matchDictList
} from "../../utils/index.js";
import Dialog from '@vant/weapp/dialog/dialog';
import Toast from '@vant/weapp/toast/toast';
Page({
	/**
	 * 页面的初始数据
	 */
	data: {
		customerAddress: "",
		sellerAddress: "",
		orderId: "",
		orderIdErrMsg: "",
		customerData: { //客户数据
			name: "",
			address: "",
			phone: "",
			regionCode: [],
			regionValue: [],
		},
		sellerData: {
			name: "",
			address: "",
			phone: "",
			regionCode: [],
			regionValue: [],
		},
		// 锁具信息
		lockInfo: {
			CTEI: "",
			type: ""
		},
		lockInfoType: "",
		uploadFiles: [],
		fileList: [],
		dicts: [],
		userInfo: {},
		text: null,
		isSubmit: false
	},
	/**
	 * 生命周期函数--监听页面加载
	 */
	onLoad: async function (options) {
		this.setData({
			dicts: getApp().globalData.dicts.lockType || []
		})
		await this.queryStandPhoto();
	},
	// 修改信息
	editInfo(e) {
		const type = e.currentTarget.dataset.data;
		if (type == '1') {
			wx.setStorageSync('customerData', JSON.stringify(this.data.customerData));
		} else {
			wx.setStorageSync('sellerData', JSON.stringify(this.data.sellerData));
		}
		wx.navigateTo({
			url: '/pages/customForm/index?type=' + type
		})
	},
	// 查询标准图片
	async queryStandPhoto() {
		// await wx.hideToast();
		wx.showLoading({
			title: '正在加载',
			mask: true
		})
		return new Promise((resolve, reject) => {
			getApp().globalData.wxCloudRequest({
				type: "queryStandPhoto",
			}).then((res) => {
				resolve(res);
				this.setData({
					fileList: res.result.data.map((item) => {
						return {
							url: item.filePath,
							name: item.fileName,
							id: item._id
						}
					})
				})
				wx.hideLoading()
			}).catch((err) => {
				reject(err);
			})
		})
	},
	getphonenumber(e) {},
	getUserInfo(e) {
		// getApp().globalData.wxCloudRequest({
		// 	type:"getPhone",
		// 	cloudID:e.detail.cloudID
		// })
		// return
		if (e.detail.errMsg == "getUserProfile:ok") {
			getApp().globalData.userInfo = {
				...e.detail.userInfo
			};
			wx.setStorageSync('userInfo', e.detail.userInfo)
			this.setData({
				userInfo: getApp().globalData.userInfo
			});
			this.placeOrder();
		}
	},
	// 下单
	async placeOrder() {
		const flag = this.validData();
		if (!flag) {
			return false;
		}
		const formData = {
			orderId: this.data.orderId,
			customerData: this.data.customerData,
			sellerData: this.data.sellerData,
			openId: getApp().globalData.idInfo.openid,
			lockInfo: this.data.lockInfo,
			createUser: this.data.userInfo //创建人对象
		}
		this.setData({
			isSubmit: true
		})
		Promise.all(this.data.uploadFiles.map((item) => {
			const fileName = item.url.split("/").pop();
			const filePath = item.url;
			return this.uploadFiles(filePath, fileName)
		})).then((fileList) => {
			let imgs = fileList.map((item) => {
				const fileName = item.fileID.split("/").pop();
				return {
					filePath: item.fileID,
					fileName: fileName
				}
			});
			getApp().globalData.wxCloudRequest({
				type: "addOrder",
				...formData,
				imgs: imgs
			}).then((order) => {
				wx.showToast({
					title: '下单成功',
					icon: "success",
					mask: true
				});
				this.setData({
					isSubmit: false,
					orderId: "",
					uploadFiles: []
				});
				// 下单成功
				wx.navigateTo({
					url: '/pages/orderSuccess/index?orderId=' + order.result._id,
				})
			}).catch((err) => {
				this.setData({
					isSubmit: false
				});
			});
		}).catch(() => {
			wx.showToast({
				title: '图片上传失败，请重新下单',
				icon: "error",
				mask: true
			})
		});
	},
	// 校验数据
	validData() {
		if (this.data.orderId == "") {
			Toast({
				type: 'fail',
				mask: true,
				forbidClick: true,
				message: "订单编号不能为空"
			});
			this.setData({
				orderIdErrMsg: "订单编号不能为空"
			})
			return
		}
		this.setData({
			orderIdErrMsg: ""
		})
		if (!this.data.customerData.name || !this.data.customerData.phone) {
			wx.showToast({
				title: '请填写客户信息',
				icon: "error",
				mask: true
			})
			return false
		}
		if (!this.data.sellerData.name || !this.data.sellerData.phone) {
			wx.showToast({
				title: '请填写卖方信息',
				icon: "error",
				mask: true
			})
			return false
		}
		if (!this.data.lockInfo.CTEI || !this.data.lockInfo.type) {
			wx.showToast({
				title: '请填写锁具信息',
				icon: "error",
				mask: true
			})
			return false
		}
		if (this.data.uploadFiles.length < 3) {
			Toast({
				type: 'fail',
				mask: true,
				forbidClick: true,
				message: "请至少上传3张图片"
			});
			return false
		}
		return true;
	},
	fieldChange(e) {
		this.setData({
			orderId: e.detail.trim()
		})
	},
	blurField() {
		if (this.data.orderId == "") {
			this.setData({
				orderIdErrMsg: "订单编号不能为空"
			})
		} else {
			this.setData({
				orderIdErrMsg: ""
			})
		}
	},
	// 上传图片
	uploadImg() {
		wx.chooseImage({
			// count: 0,
		}).then((res) => {
			this.setData({
				uploadFiles: this.data.uploadFiles.concat(res.tempFilePaths)
			})
		}).catch((err) => {})
	},
	uploadFiles(filePath, fileName) {
		return new Promise((resolve, reject) => {
			wx.cloud.uploadFile({
				// 指定上传到的云路径
				cloudPath: "userUploadFiles/" + fileName,
				// 指定要上传的文件的小程序临时文件路径
				filePath: filePath,
			}).then((res) => {
				resolve(res)
			}).catch((err) => {
				reject(err)
			})
		})
	},
	// 文件读取前
	beforeRead(e) {
		e.detail.callback(true);
	},
	// 文件读取后
	afterRead(e) {
		this.setData({
			uploadFiles: this.data.uploadFiles.concat(e.detail.file)
		})
	},
	// 删除图片
	async deletePhoto(e) {
		try {
			const modalRes = await wx.showModal({
				cancelColor: '#000000',
				title: "提示",
				content: '是否删除这张图片',
				confirmColor: "#67C23A"
			});
			if (modalRes.confirm) {
				const uploadFiles = [...this.data.uploadFiles];
				uploadFiles.splice(e.detail.index, 1);
				this.setData({
					uploadFiles: uploadFiles
				})
			}
		} catch (error) {	}
	},
	// 填写锁具信息
	toLocation() {
		wx.navigateTo({
			url: '/pages/lockInfo/index',
		})
	},
	/**
	 * 生命周期函数--监听页面初次渲染完成
	 */
	onReady: function () {},

	/**
	 * 生命周期函数--监听页面显示
	 */
	onShow: function () {
		const customerData = wx.getStorageSync('customerData') ? JSON.parse(wx.getStorageSync('customerData')) : {
			name: "",
			address: "",
			phone: "",
			regionCode: [],
			regionValue: []
		};
		const sellerData = wx.getStorageSync('sellerData') ? JSON.parse(wx.getStorageSync('sellerData')) : {
			name: "",
			address: "",
			phone: "",
			regionCode: [],
			regionValue: []
		};
		const lockInfo = wx.getStorageSync('lockInfo') || {
			CTEI: "",
			type: ""
		};
		this.setData({
			customerData: {
				...customerData
			},
			sellerData: {
				...sellerData
			},
			customerAddress: customerData.regionValue.join(""),
			sellerAddress: sellerData.regionValue.join(""),
			lockInfo: lockInfo,
			lockInfoType: matchDictList(lockInfo.type, this.data.dicts, "dictValue", "dictLabel"),
			userInfo: getApp().globalData.userInfo
		});
		wx.hideHomeButton();
	},

	/**
	 * 生命周期函数--监听页面隐藏
	 */
	onHide: function () {

	},

	/**
	 * 生命周期函数--监听页面卸载
	 */
	onUnload: function () {

	},

	/**
	 * 页面相关事件处理函数--监听用户下拉动作
	 */
	onPullDownRefresh: function () {

	},

	/**
	 * 页面上拉触底事件的处理函数
	 */
	onReachBottom: function () {

	},

	/**
	 * 用户点击右上角分享
	 */
	onShareAppMessage: function () {

	}
})